package com.yuanli.baidu.trans;

import android.util.Log;

import com.yuanli.https.OKHttpUtils;
import com.yuanli.utils.MD5EncryptUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 百度翻译工具类
 */
public class BaiduTransUtils {
    public interface BaiduTransCallBack {
        void success(String s);
        void fail();
    }


    /**
     * 百度翻译接口
     * @param text 翻译文本
     * @param from 原本语种
     * @param to 翻译语种
     * @param baiduTransCallBack 回调
     */
    public static void baiduText(String text, String from, String to, final BaiduTransCallBack baiduTransCallBack) {
        try {
            if (text.contains("\n")) {
                text = text.replace("\n", "\\n");
            }
            String q = URLDecoder.decode(text, "UTF-8");
            String appid = "20181206000244332";
            String salt = System.currentTimeMillis() + "";
            String sign = appid + q + salt + "I9Lnbi_5xhcw0cJC9dCb";
            sign = MD5EncryptUtils.MD5Encode(sign, "UTF-8").toLowerCase();
            OKHttpUtils.getHttp(OKHttpUtils.BAIDU_TEXT + "?q=" + q + "&from=" + from + "&to=" + to + "&appid=" + appid + "&salt=" + salt + "&sign=" + sign, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    Log.v("Exception e", "onFailure");
                    baiduTransCallBack.fail();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        String value = response.body().string();
                        JSONArray jsonArray = new JSONObject(value).getJSONArray("trans_result");
                        String content = "";
                        for (int i = 0; i < jsonArray.length(); i++) {
                            content += "\n" + jsonArray.getJSONObject(i).getString("dst");
                        }
                        content = content.substring(1);
                        Log.v("contentmsg", content);
                        if (content.contains(" \\ n")){
                            content= content.replace(" \\ n","\n");
                        }
                        baiduTransCallBack.success(content);

                    } catch (Exception e) {
                        Log.v("Exception e", "Exception");
                        baiduTransCallBack.fail();
                    }
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            baiduTransCallBack.fail();
        }
    }


}
